<?php
namespace AdminBundle\Model;

use AdminBundle\RBAC\Permission;
use RedUnicorn\SymfonyKernel\Appoint\Model\BuiltInDataInterface;
use RedUnicorn\SymfonyKernel\Model\Model;
use Symfony\Component\DependencyInjection\ContainerInterface;

class m_permission extends Model implements BuiltInDataInterface
{

    private $appendPermissions = [
        // 添加权限
//        ['name' => 'test_view', 'description' => '测试view'],

        // 添加角色
//        ['name' => 'test_role', 'description' => '测试角色', 'type' => Permission::TYPE_ROLE],
    ];

    public function __construct(ContainerInterface $container = null)
    {
        parent::__construct($container, 'menu');
    }

    public function validate($data, $id = false)
    {
        return true;
    }

    public function insert($data)
    {
        return true;
    }

    function update($id, $data)
    {
        return true;
    }

    public function builtInData()
    {
        $this->appendPermission($this->appendPermissions);
    }

    private function appendPermission($permissions)
    {
        $rbac = $this->get('rbac');
        foreach ($permissions as $v) {
            if (!isset($v['type']) || $v['type'] == Permission::TYPE_PERMISSION) {
                $item = $rbac->createPermission($v['name']);
            } else {
                $item = $rbac->createRole($v['name']);
            }

            $item->description = $v['description'];

            try {
                $rbac->add($item);
            } catch (\Exception $exception) {
                continue;
            }
        }
    }
}